package com.ylyq.ylxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ylyq.ylxx.entity.YlyqCreativeTitleV2;
import com.ylyq.ylxx.entity.YlyqCreativeVideoMaterial;
import com.ylyq.ylxx.entity.YlyqGroupInfo;
import com.ylyq.ylxx.mapper.YlyqGroupInfoMapper;
import com.ylyq.ylxx.model.request.SaveAutoGroupInfoRequest;
import com.ylyq.ylxx.service.IYlyqCreativeTitleV2Service;
import com.ylyq.ylxx.service.IYlyqCreativeVideoMaterialService;
import com.ylyq.ylxx.service.IYlyqGroupInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 关联计划相关信息 服务实现类
 * </p>
 *
 * @author xiaweichao
 * @since 2020-08-04
 */
@Service
public class YlyqGroupInfoServiceImpl extends ServiceImpl<YlyqGroupInfoMapper, YlyqGroupInfo> implements IYlyqGroupInfoService {
    @Autowired
    private IYlyqCreativeTitleV2Service iYlyqCreativeTitleV2Service;
    @Autowired
    private IYlyqCreativeVideoMaterialService iYlyqCreativeVideoMaterialService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAutoGroupInfo(SaveAutoGroupInfoRequest saveAutoGroupInfoRequest) {
        UpdateWrapper<YlyqCreativeVideoMaterial> videoQueryWrapper = new UpdateWrapper<>();
        videoQueryWrapper.eq("advertise_id", saveAutoGroupInfoRequest.getAdvertiserId())
                .eq("group_name", saveAutoGroupInfoRequest.getGroupName())
                .set("group_id", saveAutoGroupInfoRequest.getGroupId());
        iYlyqCreativeVideoMaterialService.update(videoQueryWrapper);

        UpdateWrapper<YlyqCreativeTitleV2> titleV2QueryWrapper = new UpdateWrapper<>();
        titleV2QueryWrapper.eq("advertise_id", saveAutoGroupInfoRequest.getAdvertiserId())
                .eq("group_name", saveAutoGroupInfoRequest.getGroupName())
                .set("group_id", saveAutoGroupInfoRequest.getGroupId());
        iYlyqCreativeTitleV2Service.update(titleV2QueryWrapper);


        QueryWrapper<YlyqGroupInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("advertiser_id", saveAutoGroupInfoRequest.getAdvertiserId());
        List<YlyqGroupInfo> ylyqGroupInfoList = list(queryWrapper);
        if (ylyqGroupInfoList != null && !ylyqGroupInfoList.isEmpty()) {
            remove(queryWrapper);
        }

        YlyqGroupInfo ylyqGroupInfo = new YlyqGroupInfo();
        BeanUtils.copyProperties(saveAutoGroupInfoRequest, ylyqGroupInfo);
        save(ylyqGroupInfo);
    }
}
